/**
 * 从 html 代码中抽取 css 和 template
 */
function extractCssAndBodyFromHtml(htmlCode: string): { css: string; template: string } {
  const cssRegex = /<style(?:\s+type="text\/css")?>([\s\S]+?)<\/style>/g;
  const bodyRegExp = /<body>([\s\S]+?)<\/body>/; // 匹配body标签中的HTML代码

  let cssCode = "";
  let bodyHtml = "";

  let match: RegExpExecArray | null;
  while ((match = cssRegex.exec(htmlCode)) !== null) {
    cssCode += match[1];
  }

  const bodyMatch = htmlCode.match(bodyRegExp);
  if (bodyMatch) {
    bodyHtml = bodyMatch[1];
  }

  return { css: cssCode, template: bodyHtml };
}

/**
 * 生成script代码
 */
function createScriptCode(): string {
  return `
      import router from '@system.router'

      export default {
        onInit() {
          console.log('onInit')
        },
        jumpTo(path) {
          // 跳转到应用内的某个页面，router 用法详见：文档 -> 接口 -> 页面路由
          router.push({
            uri: path
          })
        }
      }
  `;
}

/**
 * 将template、css、script聚合成为蓝河ux代码
 */
function createUxCode(template: string, css: string, script: string): string {
  return `
    <template>${template}</template>
    <script>${script}</script>
    <style>${css}</style>
  `;
}

/**
 * 替换标签（支持成对标签和自闭合标签）
 */
function replaceTag(htmlString: string, originalTag: string, newTag: string): string {
  // 处理成对标签（带内容）
  const pairPattern = new RegExp(`<${originalTag}([^>]*)>([\\s\\S]*?)<\/${originalTag}>`, 'gi');
  let replaced = htmlString.replace(pairPattern, (match, attrs, content) => {
    console.log(match)
    return `<${newTag}${attrs}>${content}</${newTag}>`;
  });

  // 处理自闭合标签（无内容）
  const selfClosingPattern = new RegExp(`<${originalTag}([^>]+?)\\s*\/?>`, 'gi');
  replaced = replaced.replace(selfClosingPattern, (match, attrs) => {
    console.log(match)
    return `<${newTag}${attrs}></${newTag}>`;
  });

  return replaced;
}

const tagMap: Record<string, string> = {
  h1: "text",
  h2: "text",
  h3: "text",
  h4: "text",
  h5: "text",
  h6: "text",
  p: "text",
  span: "text",
  button: "text",
  header: "div",
  main: "div",
  section: "div",
  footer: "div",
  img: "image",
  input: "input"
};

/**
 * 通过 html 生成 blueos 代码
 */
export function convertToBlueOSCodeFromHtml(htmlCode: string): string {
  // 抽取 css 和 template
  let { css, template } = extractCssAndBodyFromHtml(htmlCode);
  
  // html 的标签转换为蓝河组件
  Object.keys(tagMap).forEach((tag) => {
    template = replaceTag(template, tag, tagMap[tag]);
  });

  // 创建 js 代码
  const script = createScriptCode();
  
  // 将 css、template、js 组装为蓝河代码
  return createUxCode(template, css, script);
}
